package com.example.sql.manager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.sql.manager.dao.FuncDao;
import com.example.sql.manager.entity.po.FuncPO;
import com.example.sql.manager.service.FuncService;
import com.example.sql.manager.utils.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
@Transactional
public class FuncServiceImpl implements FuncService {

    @Resource
    private FuncDao funcDao;

    @Override
    public Long saveFunc(FuncPO func) throws Exception {
        //对 title, content, description, enabled字段进行摘要计算
        String md5 = this.getFuncMd5(func);
        //唯一索引
        func.setMd5(md5);
        if (null == func.getId()) {
            //没有id插入
            func.setId(IDUtils.genRandomId());
            InsertUtils.fillObj(func);
            this.funcDao.insert(func);
        } else {
            //有id更新
            FuncPO dbFunc = this.funcDao.selectById(func.getId());
            if (Objects.nonNull(dbFunc)) {
                UpdateTools.mergeProperties(dbFunc, func);
                UpdateUtils.fillObj(func);
            }
            this.funcDao.updateById(func);
        }
        //todo 以文件的形式备份SQL文，防止有人使坏通过API存入删库SQL脚本

        return func.getId();
    }

    private String getFuncMd5(FuncPO func) {
        String info = StringUtils.concat(func.getTitle(), func.getContent()
                , func.getDescription(), String.valueOf(func.getEnabled()));
        return Md5Utils.md5DigestAsHex(info);
    }

    @Override
    public FuncPO getById(Long functionId) {
        return this.funcDao.selectById(functionId);
    }

    @Override
    public List<FuncPO> sqlList() {
        QueryWrapper<FuncPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_date");
        return this.funcDao.selectList(queryWrapper);
    }
}
